import React, {useState, useRef, useEffect, useContext} from 'react';
import Coder, {CoderMethots} from '../Components/Coder';
import {Button, Select, Card} from 'antd'
import {
    Topic,
    SubTopic, getSubTopics,
    getWordData,
    getTopics
} from '../data/topic/topic';
import {
    splitRow,

} from '../data'

const Option = Select.Option
import styles from './index.less'

interface PageType {
    changeCode: (codeData: any[]) => void
}

export const SubTopicContext = React.createContext({});

function SelectBar(props: PageType) {

    const {changeCode} = props
    // @ts-ignore
    const {setSubTopicId} = useContext(SubTopicContext);


    //当前选择的字符类型
    const [select, setSelect] = useState<SubTopic>()

    //当前的主题
    const [topic, setTopic] = useState<Topic>()
    const [topicArr, setTopicArr] = useState<Array<Topic>>()
    let [subTopicArr, setSubTopicArr] = useState<Array<SubTopic>>()

    useEffect(() => {
        if (!topicArr) {
            (async () => {
                let res = await getTopics()
                setTopicArr(res.data)
                let data = res.data;
                if (data.length) {
                    setTopic(data[0])
                }
            })()
        }
    }, [topicArr])

    //当主题发生变换时
    useEffect(() => {

        if (topic) {
            getSubTopics(topic.id).then(res => {
                subTopicArr = res.data
                setSubTopicArr(res.data)
                let curSub = res.data


                if (curSub.length != 0) {
                    doChangeSelect(curSub[0].id + '')

                }

            })
        }

    }, [topic])

    function changeTopic(value: string) {
        let curTopic = topicArr?.find(item => item.topicCode == value)
        if (curTopic) {
            setTopic(curTopic)
        }

    }

    function changeSelect(value: string) {

        doChangeSelect(value)
    }

    function doChangeSelect(value: string) {

        let curSubTopic = subTopicArr?.find(item => item.id + '' == value);
        setSelect(curSubTopic)

        let curTopic = topic;

        if (curTopic && curSubTopic) {
            getWordData(curTopic.key, curSubTopic?.params).then(res => {
                let data = splitRow(res.data)
                setSubTopicId(curSubTopic?.id)
                changeCode(data)
            })
        }

    }

    return (<>
        <Select className="select" value={topic?.topicCode} onChange={changeTopic} style={{width: 160}}>
            {
                topicArr?.map((item: Topic) => {
                    return <Option key={item.id} value={item.topicCode}>{item.name}</Option>
                })
            }
        </Select>
        <Select className="select" value={(select?.id + '')} onChange={changeSelect} style={{width: 220}}>

            {
                subTopicArr?.map(item => {
                    return <Option key={item.id} value={item.id + ''}>{item.name}</Option>
                })
            }
        </Select>
    </>)

}


export function Practice() {
    //当前选择的字符类型

    const [subTopicId, setSubTopicId] = useState(0)
    const [practiceTopicId, setPracticeTopicId] = useState(0)

    //显示的速度
    const [speed, setSpeed] = useState('')

    //显示的正确率
    const [correct, setCorrect] = useState('')

    //当前渲染的字符
    const [codeData, setCodeData] = useState<any[]>([])
    const [coderKey, updateCoderKey] = useState('')
    const [isStart, setIsStart] = useState(false)
    const codeRef = useRef<CoderMethots>(null)


    useEffect(() => {
        if (coderKey && isStart) {
            const coder = codeRef.current
            if (coder) {
                coder.start()
            }
        }

    }, [coderKey, isStart])


    function changeCode(codeData: any[]) {
        updateCoderKey(Math.random() + '' + new Date().getTime())
        setIsStart(false)
        setCodeData(codeData)
    }


    function start() {
        updateCoderKey(Math.random() + '' + new Date().getTime())
        setIsStart(true)
    }

    function restart() {
        updateCoderKey(Math.random() + '' + new Date().getTime())
        setIsStart(true)
    }

    function end(speed: string, correct: string) {
        setSpeed(speed)
        setCorrect(correct)
    }


    return (<>

        <SubTopicContext.Provider value={
            {
                subTopicId, setSubTopicId,
                practiceTopicId, setPracticeTopicId
            }
        }>
            <div>
                <SelectBar changeCode={changeCode}/>

                {/*<button className="button ml-sm" onClick={start}>开始</button>*/}

                {/*<button className="button ml-sm" onClick={restart}>重新开始</button>*/}
                <Button type="primary" onClick={start}>开始</Button>
                <Button type="primary" onClick={restart}>重新开始</Button>
            </div>

            <div className={styles.result}>
                {speed && correct && <p><span>速度：{speed}</span> &nbsp; &nbsp;<span>正确率：{correct}</span></p>}
            </div>
            <Coder key={coderKey} ref={codeRef} code={codeData} end={end}/>
        </SubTopicContext.Provider>


    </>)
}
export default React.forwardRef(Practice)